<?php

namespace App\Core\Traits;

trait Numeral
{

    /**
     * 数字位数(包括小数)
     *
     * @var string
     */
    protected $decimals;

    /**
     * 小数点位数
     *
     * @var int
     */
    protected $precision;

    /**
     * 数字位数(包括小数)
     *
     * @return int
     */
    public function decimals(): int
    {
        if (is_null($this->decimals)) {
            $this->decimals = config('system.numeral.decimals');
        }
        return $this->decimals;
    }

    /**
     * 小数点位数
     *
     * @return int
     */
    public function precision(): int
    {
        if (is_null($this->precision)) {
            $this->precision = config('system.numeral.precision');
        }
        return $this->precision;
    }

    /**
     * 对浮点数进行四舍五入
     *
     * @param number $num
     * @param int $precision
     * @return number
     */
    public function makeRound($num, $precision = null)
    {
        return round($num, $precision ?: $this->precision(), PHP_ROUND_HALF_DOWN);
    }

    /**
     * 计算概率，并处理除数为零的情况
     *
     * @param number $dividend
     * @param number $divisor
     * @param int $precision
     * @return number
     */
    public function makeRate($dividend, $divisor, $precision = null)
    {
        return !floatval($dividend) || !floatval($divisor) ? 0 : $this->makeRound($dividend / $divisor, $precision);
    }

    /**
     * 计算RTP，并处理除数为零的情况
     *
     * @param number $bet
     * @param number $gain
     * @param int $precision
     * @return number
     */
    public function makeRtp($bet, $gain, $precision = null)
    {
        return $bet == 0 ? 1 : $this->makeRound(1 + $gain / $bet, $precision);
    }

    /**
     * 科学计数转数字
     *
     * @param number $num
     * @param int $decimals
     * @param int $precision
     * @return number
     */
    public function exponentialToNumber($num, $decimals = null, $precision = null)
    {
        if (false === stripos($num, 'e')) {
            return $num;
        }
        return $this->makeRound(number_format($num, $decimals ?: $this->decimals(), '.', ''), $precision);
    }
}
